/*
;layui.define(function(e) {
    layui.use(['table','layer','form','laydate'], function(){
        var $ = layui.$
            ,layer = layui.layer
            ,form = layui.form
            ,table = layui.table
            ,laydate = layui.laydate;
        
        var dealer1 = table.render({
              elem: '#dealer1'
            , loading: true
            , id: 'listReload'//生成 Layui table 的标识 id，必须提供，用于后文刷新操作
            , url: hostUrl + '/dealer/searchDealerAndStore'
              ,cols: [[ //标题栏
                  {field: 'store_code', title: '门店编号',minWidth:110,templet:'#storeItem'}
                  ,{field: 'store_name', title: '门店名称',minWidth:200,}
                   ,{field: 'store_province', title: '省'}
                  ,{field: 'store_city', title: '市'}
                  ,{field: 'store_town', title: '县/区'}
                  ,{field: 'store_address', title: '门店详细地址'}
                  ,{field: 'legalperson_name', title: '法人姓名'}
                  ,{field: 'legalperson_sex', title: '法人性别'}
                  ,{field: 'legalperson_phone', title: '法人电话'}
                  ,{field: 'actualperson_name', title: '实际控制人姓名'}
                  ,{field: 'actualperson_sex', title: '实际控制人性别'}
                  ,{field: 'actualperson_phone', title: '实际控制人电话'}
                  ,{field: 'create_time', title: '创建日期',width: 180} 
                  ,{field: 'tool',title: '操作', minWidth:200, align:'center', toolbar: '#operationMangerBar',fixed: 'right'}
              ]]
              ,cellMinWidth: 120
//             ,data: dealerData
              ,page: true //是否显示分页
             ,done: function (res, curr, count) {
                 layuiRowspan('store_name','store_province','store_city','store_town','store_address',
                		 'legalperson_name','legalperson_sex','legalperson_phone',
                		 'actualperson_name','actualperson_sex','actualperson_phone',1);
              }
        
         });
       // form.render()
       //表刷新方法
        var reloadTable = function () {
                table.reload("listReload", { //此处是上文提到的 初始化标识id
                where: {
                	 dealerName: $("#dealerName").val(),
                     storeName: $("#storeName").val(),
                      
                }
            });
        };

        // 查询按钮绑定点击事件
        $("#searchBtn").on("click", function () {
            reloadTable();
        }) 
      
        //监听工具条
	         table.on('tool(dealer1ListTable)', function(obj){
	             var data = obj.data;
	             if(obj.event === 'dealerEdit'){
	                 dealerEdit();
	             } else if(obj.event === 'look'){
	                 var index = layer.open({
	                     type: 2
	                     ,id: (new Date()).valueOf()
	                     ,title: '查看'
	                     ,content: 'look.html'
	                     ,area: ['500px', '500px']
	                     ,btn: ['保存', '取消']
	                     ,maxmin: true
	                     ,success: function(layero, index){
	                         var body = layer.getChildFrame('body', index);
	                         var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
//	                         console.log(body.html()) //得到iframe页的body内容
//	                          var paramId=body.find("input[name='id']");
//	                          paramId.val(111);
	                     }
	                     ,yes: function (layero, index) {
	                         // layer.alert("保存按钮");
	                         return false //开启该代码可禁止点击该按钮关闭
	                     }
	                     ,btn2: function (layero, index) {
	                         layer.alert("取消按钮")
	                         //return false 开启该代码可禁止点击该按钮关闭
	                     }
	                 });
	                 layer.full(index);
	             }else if(obj.event === 'edit'){
	                 storeEdit()
	             }else if(obj.event === 'recover'){
	                 layer.confirm('确定恢复吗?', function(index){
	                     layer.close(index);
	                 });
	             }else if(obj.event === 'delete'){
	                 layer.confirm('确定注销吗?', function(index){
	                     obj.del();
	                     layer.close(index);
	                 });
	             }
	         }); 
        
   
        
        //执行一个laydate实例
        laydate.render({
            elem: '#date'
        });
        $("#addDealer").click(function () {
            dealerEdit()
        })
        $("#addStore").click(function () {
            storeEdit()
        })

        //执行一个laydate日期实例
        laydate.render({
            elem: '#date'
        });
        form.render()
        
        function dealerEdit() {
            var index = layer.open({
                type: 2
                ,id: (new Date()).valueOf()
                ,title: '编辑'
                ,content: 'dealerEdit.html'
                ,area: ['500px', '500px']
                ,btn: ['保存', '取消']
                ,maxmin: true
                ,success: function(layero, index){
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
//                        console.log(body.html()) //得到iframe页的body内容
//                         var paramId=body.find("input[name='id']");
//                         paramId.val(111);
                }
                ,yes: function (layero, index) {
                     layer.alert("确定按钮");
                    return false //开启该代码可禁止点击该按钮关闭
                }
                ,btn2: function (layero, index) {
                    layer.alert("取消按钮")
                    //return false 开启该代码可禁止点击该按钮关闭
                }
            });
            layer.full(index);
        }
        function storeEdit() {
            var index = layer.open({
                type: 2
                ,id: (new Date()).valueOf()
                ,title: '编辑'
                ,content: 'storeEdit.html'
                ,area: ['500px', '500px']
                ,btn: ['保存', '取消']
                ,maxmin: true
                ,success: function(layero, index){
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
//                        console.log(body.html()) //得到iframe页的body内容
//                         var paramId=body.find("input[name='id']");
//                         paramId.val(111);
                }
                ,yes: function (layero, index) {
                    layer.alert("确定按钮");
                    return false //开启该代码可禁止点击该按钮关闭
                }
                ,btn2: function (layero, index) {
                    layer.alert("取消按钮")
                    //return false 开启该代码可禁止点击该按钮关闭
                }
            });
            layer.full(index);
        }
        *//**
         * 合并单元格*//*
        function layuiRowspan() {
            var execRowspan = function(fieldName,index,flag){
                // 1为不冻结的情况，左侧列为冻结的情况
                let fixedNode = index=="1"?$(".layui-table-body")[index - 1]:(index=="3"?$(".layui-table-fixed-r"):$(".layui-table-fixed-l"));
                // 左侧导航栏不冻结的情况
                let child = $(fixedNode).find("td");
                let childFilterArr = [];
                // 获取data-field属性为fieldName的td
                for(let i = 0; i < child.length; i++){
                    if(child[i].getAttribute("data-field") == fieldName){
                        childFilterArr.push(child[i]);
                    }
                }
                // 获取td的个数和种类
                let childFilterTextObj = {};
                for(let i = 0; i < childFilterArr.length; i++){
                    let childText = flag?childFilterArr[i].innerHTML:childFilterArr[i].textContent;
                    if(childFilterTextObj[childText] == undefined){
                        childFilterTextObj[childText] = 1;
                    }else{
                        let num = childFilterTextObj[childText];
                        childFilterTextObj[childText] = num*1 + 1;
                    }
                }
                let canRowspan = true;
                let maxNum;//以前列单元格为基础获取的最大合并数
                let finalNextIndex;//获取其下第一个不合并单元格的index
                let finalNextKey;//获取其下第一个不合并单元格的值
                for(let i = 0; i < childFilterArr.length; i++){
                    (maxNum>9000||!maxNum)&&(maxNum = $(childFilterArr[i]).prev().attr("rowspan")&&fieldName!="8"?$(childFilterArr[i]).prev().attr("rowspan"):9999);
                    let key = flag?childFilterArr[i].innerHTML:childFilterArr[i].textContent;//获取下一个单元格的值
                    let nextIndex = i+1;
                    let tdNum = childFilterTextObj[key];
                    let curNum = maxNum<tdNum?maxNum:tdNum;
                    if(canRowspan){
                        for(let j =1;j<=curNum&&(i+j<childFilterArr.length);){//循环获取最终合并数及finalNext的index和key
                            finalNextKey = flag?childFilterArr[i+j].innerHTML:childFilterArr[i+j].textContent;
                            finalNextIndex = i+j;
                            if((key!=finalNextKey&&curNum>1)||maxNum == j){
                                canRowspan = true;
                                curNum = j;
                                break;
                            }
                            j++;
                            if((i+j)==childFilterArr.length){
                                finalNextKey=undefined;
                                finalNextIndex=i+j;
                                break;
                            }
                        }
                        childFilterArr[i].setAttribute("rowspan",curNum);
                        if($(childFilterArr[i]).find("div.rowspan").length>0){//设置td内的div.rowspan高度适应合并后的高度
                            $(childFilterArr[i]).find("div.rowspan").parent("div.layui-table-cell").addClass("rowspanParent");
                            $(childFilterArr[i]).find("div.layui-table-cell")[0].style.height= curNum*38-10 +"px";
                        }
                        canRowspan = false;
                    }else{
                        childFilterArr[i].style.display = "none";
                    }
                    if(--childFilterTextObj[key]==0|--maxNum==0|--curNum==0|(finalNextKey!=undefined&&nextIndex==finalNextIndex)){//||(finalNextKey!=undefined&&key!=finalNextKey)
                        canRowspan = true;
                    }
                }
            }
            //合并数据表格行
            var layuiRowspan = function(fieldNameTmp,index,flag){
                let fieldName = [];
                if(typeof fieldNameTmp == "string"){
                    fieldName.push(fieldNameTmp);
                }else{
                    fieldName = fieldName.concat(fieldNameTmp);
                }
                for(let i = 0;i<fieldName.length;i++){
                    execRowspan(fieldName[i],index,flag);
                }
            }
        }
    });
    //输出模块
   */
layui.use(['table','layer','form','laydate'], function () {
    var table = layui.table
        , element = layui.element;
    //展示已知数据
    table.render({
        elem: '#dealer1'
        , id: 'listReload'//生成 Layui table 的标识 id，必须提供，用于后文刷新操作
        , url: hostUrl + '/dealer/searchDealerAndStore'
        , page: {theme: '#a3c93f'}
        , loading: true
        , cellMinWidth: 120 //全局定义常规单元格的最小宽度
        , cols: [[ //标题栏
        	 {field: 'store_code', title: '门店编号',minWidth:110,templet:'#storeItem'}
             ,{field: 'store_name', title: '门店名称',minWidth:200,}
              ,{field: 'store_province', title: '省'}
             ,{field: 'store_city', title: '市'}
             ,{field: 'store_town', title: '县/区'}
             ,{field: 'store_address', title: '门店详细地址'}
             ,{field: 'legalperson_name', title: '法人姓名'}
             ,{field: 'legalperson_sex', title: '法人性别'}
             ,{field: 'legalperson_phone', title: '法人电话'}
             ,{field: 'actualperson_name', title: '实际控制人姓名'}
             ,{field: 'actualperson_sex', title: '实际控制人性别'}
             ,{field: 'actualperson_phone', title: '实际控制人电话'}
             ,{field: 'createTimeStore', title: '创建日期',width: 180} 
             ,{field: 'tool',title: '操作', minWidth:200, align:'center', toolbar: '#operationMangerBar',fixed: 'right'}
         ]]
         ,cellMinWidth: 120
//        ,data: dealerData
         ,page: true //是否显示分页
        ,done: function (res, curr, count) {
        	$('.layui-table-fixed-r').removeClass('layui-hide');
            layuiRowspan('store_name','store_province','store_city','store_town','store_address',
           		 'legalperson_name','legalperson_sex','legalperson_phone',
           		 'actualperson_name','actualperson_sex','actualperson_phone',1);
         }
    });
    //表刷新方法
    var reloadTable = function () {
        var date = $("#start-end-date").val();
        var startDate = "", endDate = "";
        if (date != null && date != undefined && date.length > 0) {
            startDate = date.split(" - ")[0];
            endDate = date.split(" - ")[1];
        }
        table.reload("listReload", { //此处是上文提到的 初始化标识id
            where: {
            	dealerName: $("#dealerName").val(),
                storeName: $("#storeName").val(),
                startDate: $("#startDate").val(),
                endDate: $("#endDate").val()
            }
        });
    };

    // 查询按钮绑定点击事件
    $("#searchBtn").on("click", function () {
        reloadTable();
    })
   
 
  //监听工具条
    table.on('tool(dealer1ListTable)', function(obj){
        var data = obj.data;
         if(obj.event === 'dealerEdit'){
         		 
         	dataDetail=data;
        	var detail=layer.open({
                type: 2
                ,id: (new Date()).valueOf()
                ,title: '编辑经销商'
                ,content: hostUrl+'/store/dealerEdit.do'
                ,area:  ['500px', '500px']
                ,maxmin: true
                ,end: function(){
                	dataDetail=null;
                }
            }); 
        	layer.full(detail);
        } else if(obj.event === 'look'){
        	dataDetail=data;
         	var detail=layer.open({
                type: 2
                ,id: (new Date()).valueOf()
                ,title: '门店详情'
                ,content: hostUrl+'/store/storeDetail.do'
                ,area:  ['500px', '500px']
                ,maxmin: true
                ,end: function(){
                	dataDetail=null;
                }
            }); 
        	layer.full(detail);
        }else if(obj.event === 'edit'){
        	dataDetail=data;
        	var detail=layer.open({
                type: 2
                ,id: (new Date()).valueOf()
                ,title: '编辑门店'
                ,content: hostUrl+'/store/storeEdit.do'
                ,area:  ['500px', '500px']
                ,maxmin: true
                ,end: function(){
                	dataDetail=null;
                }
            }); 
        	layer.full(detail);
        }else if(obj.event === 'recover'){
            layer.confirm('确定恢复吗?', function(index){
                layer.close(index);
            });
        }else if(obj.event === 'delete'){
            layer.confirm('确定注销吗?', function(index){
            	var storeId=data.storeId;
            	var dealerId=data.dealer_id; 
             	 $.axse(
           		        hostUrl + "/dealer/storeCancel",
           		        {"storeId":storeId,"islock":'1',"dealerId":dealerId},
           		        function (obj) {
           		        	if(obj.status=='0'){
                                 
           		        		Layer.showSucMsg("注销成功");
           		        		location.reload();
           		        		
        						}else{
        							
        							Layer.showSucMsg("注销失败");
        						}
           		        },
           		        function () {
           		            layer.msg("请求失败");
           		        }
           		    )
            });
        }else if(obj.event === 'deleteDealer'){
            layer.confirm('确定注销该经销商及下所有门店吗?', function(index){
             	var dealerId=data.dealerId;
             	 $.axse(
           		        hostUrl + "/dealer/dealerCancel",
           		        { "islock":'1',"dealerId":dealerId},
           		        function (obj) {
           		        	if(obj.status=='0'){
                                 
           		        		Layer.showSucMsg("注销成功");
           		        		location.reload();
           		        		
        						}else{
        							
        							Layer.showSucMsg("注销失败");
        						}
           		        },
           		        function () {
           		            layer.msg("请求失败");
           		        }
           		    )
            });
        }
    }); 
});
 
 
function layuiRowspan() {
   var execRowspan = function(fieldName,index,flag){
       // 1为不冻结的情况，左侧列为冻结的情况
       let fixedNode = index=="1"?$(".layui-table-body")[index - 1]:(index=="3"?$(".layui-table-fixed-r"):$(".layui-table-fixed-l"));
       // 左侧导航栏不冻结的情况
       let child = $(fixedNode).find("td");
       let childFilterArr = [];
       // 获取data-field属性为fieldName的td
       for(let i = 0; i < child.length; i++){
           if(child[i].getAttribute("data-field") == fieldName){
               childFilterArr.push(child[i]);
           }
       }
       // 获取td的个数和种类
       let childFilterTextObj = {};
       for(let i = 0; i < childFilterArr.length; i++){
           let childText = flag?childFilterArr[i].innerHTML:childFilterArr[i].textContent;
           if(childFilterTextObj[childText] == undefined){
               childFilterTextObj[childText] = 1;
           }else{
               let num = childFilterTextObj[childText];
               childFilterTextObj[childText] = num*1 + 1;
           }
       }
       let canRowspan = true;
       let maxNum;//以前列单元格为基础获取的最大合并数
       let finalNextIndex;//获取其下第一个不合并单元格的index
       let finalNextKey;//获取其下第一个不合并单元格的值
       for(let i = 0; i < childFilterArr.length; i++){
           (maxNum>9000||!maxNum)&&(maxNum = $(childFilterArr[i]).prev().attr("rowspan")&&fieldName!="8"?$(childFilterArr[i]).prev().attr("rowspan"):9999);
           let key = flag?childFilterArr[i].innerHTML:childFilterArr[i].textContent;//获取下一个单元格的值
           let nextIndex = i+1;
           let tdNum = childFilterTextObj[key];
           let curNum = maxNum<tdNum?maxNum:tdNum;
           if(canRowspan){
               for(let j =1;j<=curNum&&(i+j<childFilterArr.length);){//循环获取最终合并数及finalNext的index和key
                   finalNextKey = flag?childFilterArr[i+j].innerHTML:childFilterArr[i+j].textContent;
                   finalNextIndex = i+j;
                   if((key!=finalNextKey&&curNum>1)||maxNum == j){
                       canRowspan = true;
                       curNum = j;
                       break;
                   }
                   j++;
                   if((i+j)==childFilterArr.length){
                       finalNextKey=undefined;
                       finalNextIndex=i+j;
                       break;
                   }
               }
               childFilterArr[i].setAttribute("rowspan",curNum);
               if($(childFilterArr[i]).find("div.rowspan").length>0){//设置td内的div.rowspan高度适应合并后的高度
                   $(childFilterArr[i]).find("div.rowspan").parent("div.layui-table-cell").addClass("rowspanParent");
                   $(childFilterArr[i]).find("div.layui-table-cell")[0].style.height= curNum*38-10 +"px";
               }
               canRowspan = false;
           }else{
               childFilterArr[i].style.display = "none";
           }
           if(--childFilterTextObj[key]==0|--maxNum==0|--curNum==0|(finalNextKey!=undefined&&nextIndex==finalNextIndex)){//||(finalNextKey!=undefined&&key!=finalNextKey)
               canRowspan = true;
           }
       }
   }
   //合并数据表格行
   var layuiRowspan = function(fieldNameTmp,index,flag){
       let fieldName = [];
       if(typeof fieldNameTmp == "string"){
           fieldName.push(fieldNameTmp);
       }else{
           fieldName = fieldName.concat(fieldNameTmp);
       }
       for(let i = 0;i<fieldName.length;i++){
           execRowspan(fieldName[i],index,flag);
       }
   }
}
$("#addDealer").click(function () {
	dealerAdd();
})
  function dealerAdd() {
            var index = layer.open({
                type: 2
                ,id: (new Date()).valueOf()
                ,title: '新建经销商'
                //,content: 'dealerAdd.do'
                ,content: hostUrl+'/store/dealerAdd.do'
                ,area: ['500px', '500px']
//                ,btn: ['保存', '取消']
                ,maxmin: true
                ,yes: function (layero,index) {
                	 
                }
                ,btn2: function (index, layero) {
                	 layer.close(index);
                }
            });
            layer.full(index);
        }

$("#addStore").click(function () {
    storeAdd()
})
 
 //新建门店
 function storeAdd() {
            var index = layer.open({
                type: 2
                ,id: (new Date()).valueOf()
                ,title: '新建门店'
                //,content: 'dealerAdd.do'
                ,content: hostUrl+'/store/storeAdd.do'
                ,area: ['500px', '500px']
//                ,btn: ['保存', '取消']
                ,maxmin: true
                ,yes: function (layero,index) {
                	 
                }
                ,btn2: function (index, layero) {
                	 layer.close(index);
                }
            });
            layer.full(index);
        }
